package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *  文件上传
 * @Author:wyp
 * @Date:2020/6/1 9:39
 */
@WebServlet("/uploadImages")
public class UploadController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
        //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
        String savePath = this.getServletContext().getRealPath("/img/PlaceImg");
        if("routes".equals(req.getParameter("file"))){
            savePath = this.getServletContext().getRealPath("/img/RoutesImg");
        }

        File file = new File(savePath);
        //判断上传文件的保存目录是否存在
        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath + "目录不存在，需要创建");
            file.mkdir();
        }

        //创建DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决中文乱码
        upload.setHeaderEncoding("UTF-8");

        //判断提交的数据是否是表单的数据
        if(! ServletFileUpload.isMultipartContent(req)){
            return;
        }
        //使用ServletFileUpload解析器返回是List集合
        try {
            List<FileItem> list = upload.parseRequest(req);
            for(FileItem item:list){
                //如果fileitem中封装的是普通输入项的数据
                if(item.isFormField()) {
                    String name = item.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");
                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                    System.out.println(name + "=" + value);
                }else {
                    //如果是文件类型
                    String filename = item.getName();
                    System.out.println(filename);
                    //处理获取到的上传文件的文件名的路径部分，只保留文件名部分
                    filename = filename.substring(filename.lastIndexOf("\\")+1);
                    //获取上传文件的输入流
                    InputStream in = item.getInputStream();
                    //创建文件输出流
                    FileOutputStream out = new FileOutputStream(savePath+"\\"+filename);
                    //创建缓冲区
                    byte[] buffer=new byte[1024];
                    //判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    //将输入流读入缓冲区
                    while ((len=in.read(buffer))>0){
                        out.write(buffer,0,len);
                    }
                    Map<String,String> map = new HashMap<>() ;
                    System.out.println("savePath："+savePath);
                    System.out.println("filename:"+filename);
                    if("routes".equals(req.getParameter("file"))){
                        map.put("filePath","/img/RoutesImg/"+filename);
                    }else {
                        map.put("filePath","/img/PlaceImg/"+filename);
                    }

                    map.put("code","0");
                    //关闭输入流、输出流
                    in.close();
                    out.close();
                    //删除临时生成文件
                    item.delete();

                    String result = JSONObject.toJSONString(map);
                    System.out.println(result);
                    resp.getWriter().write(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
